package com.edu.whty.service.impl;

import com.edu.whty.common.tools.UUIDUtils;
import com.edu.whty.dao.TbCommentsMapper;
import com.edu.whty.dao.TbCourseResMapper;
import com.edu.whty.dao.TbTeachingResPackageDao;
import com.edu.whty.dao.TeachingResDao;
import com.edu.whty.entity.base.CloudPage;
import com.edu.whty.entity.base.PageInfo;
import com.edu.whty.entity.base.PageList;
import com.edu.whty.entity.cloud.TbTeachingRes;
import com.edu.whty.entity.cloud.TbTeachingResPackage;
import com.edu.whty.entity.cloud.TeachingResPackageReq;
import com.edu.whty.entity.cloud.TeachingResReq;
import com.edu.whty.entity.comment.CommentsReq;
import com.edu.whty.entity.comment.TbComments;
import com.edu.whty.entity.comment.TbScore;
import com.edu.whty.service.TeachingResService;
import com.edu.whty.service.base.impl.CommonServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service("teachingResService")
@Transactional
public class TeachingResServiceImpl extends CommonServiceImpl implements TeachingResService {

	private static Logger logger = LoggerFactory.getLogger(TeachingResServiceImpl.class);

	@Autowired
	private TbCommentsMapper tbCommentsMapper;

	@Autowired
	private TbCourseResMapper tbCourseResMapper;

	@Autowired
	private TeachingResDao teachingResDao;

	@Autowired
	private TbTeachingResPackageDao tbTeachingResPackageDao;

	public TeachingResServiceImpl() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public Map<String, Object> addComment(CommentsReq comments, String netIp) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("userId", comments.getUserId());
		resultMap.put("businessId", comments.getBusinessId());
		if (null != comments.getScore()) {
			TbScore tbScoreObj = tbCommentsMapper.getScore(comments);
			if (null != tbScoreObj) {
				// 评分已存在，不能重复评分
				resultMap.put("code", "1");
				return resultMap;
			} else {
				// 保存评分
				TbScore tbScore = new TbScore();
				String id = UUIDUtils.getRandomUUID();
				tbScore.setId(id);
				/*
				 * 1共享资源，2精品资源，3共享课件，4精品课件，5教育云资源，6我的课堂,11一师一优课
				 * 9课程社区资源
				 */
				tbScore.setBusinessType(comments.getBusinessType());
				tbScore.setBusinessId(comments.getBusinessId());
				tbScore.setScore(comments.getScore());
				tbScore.setUserId(comments.getUserId());
				tbScore.setPlatformCode(comments.getPlatformCode());
				tbScore.setLoginPlatformCode(comments.getLoginPlatformCode());
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				tbScore.setCreateTime(sdf.format(new Date()));
				tbScore.setUpdateTime(sdf.format(new Date()));
				tbScore.setStatus("0");
				tbCommentsMapper.saveScore(tbScore);
			}
		}

		// 保存评论
		for(String content : comments.getContents()) {
			// 对评论的敏感词进行替换
//			String url = SysConfig.getStrValue("sensitive_url");
//			JSONObject jsonObject = new JSONObject();
//			jsonObject.put("context", content);// 文本
//			jsonObject.put("targetpersonid", comments.getUserId());// 文本所属人
//			jsonObject.put("posttimedes", new String(System.currentTimeMillis() + ""));// 请求时间
//			String param = jsonObject.toString();
//			logger.info("敏感词检测接口:" + url);
//			logger.info("参数:" + param);
//			String resp = HttpClientUtil.post(url, param, netIp);
//			if (StringUtils.isNotEmpty(resp)) {
//				com.alibaba.fastjson.JSONObject resultJson = com.alibaba.fastjson.JSONObject.parseObject(resp);
//				if ("000000".equals(resultJson.get("result"))) {
//					// 无敏感词
//					comments.setContent(content);
//				} else if ("000001".equals(resultJson.get("result"))) {
//					// 将处理后的字符串,入库
//					comments.setContent(filterInfo(comments, resultJson));
//				}
//			}
			TbComments tbComments = new TbComments();
			String aid = UUIDUtils.getRandomUUID();
			tbComments.setId(aid);
			tbComments.setAccount(comments.getAccount());
			tbComments.setBusinessType(comments.getBusinessType());
			tbComments.setBusinessId(comments.getBusinessId());
			tbComments.setContent(content);
			tbComments.setCreateTime(new Date());
			tbComments.setImgUrl(comments.getImgUrl());
			tbComments.setParentId(comments.getParentId());
			tbComments.setPlatformCode(comments.getPlatformCode());
			tbComments.setRealName(comments.getRealName());
			tbComments.setReplyedCommentId(comments.getReplyedCommentId());
			tbComments.setReplyedRealName(comments.getReplyedRealName());
			tbComments.setReplyedUserId(comments.getReplyedUserId());
			tbComments.setReplyedPlatformCode(comments.getReplyedPlatformCode());
			tbComments.setType(comments.getType());
			tbComments.setUserId(comments.getUserId());
			tbComments.setWorkspaceUrl("&sid=" + comments.getUserId());
			tbComments.setReplyedWorkspaceUrl("&sid=" + comments.getReplyedUserId());
			tbComments.setUpdateTime(new Date());
			tbComments.setLoginPlatformCode(comments.getLoginPlatformCode());
			tbComments.setReplyedLoginPlatformCode(comments.getReplyedLoginPlatformCode());
			tbComments.setBusinessSubType(comments.getBusinessSubType());
			tbComments.setBusinessSubId(comments.getBusinessSubId());
			tbComments.setStatus("0");
			tbCommentsMapper.save(tbComments);
			resultMap.put("id", aid);
		}

		/**处理业务数据**/
		if ("11".equals(comments.getBusinessType())) { //一师一优课
			Map<String, Object> map = new HashMap<String, Object>();
			String pkid = comments.getBusinessId();
			TbTeachingResPackage tResPackage = tbTeachingResPackageDao.getById(pkid);
			if(null != tResPackage){
				map.put("pkid", pkid);
				if ( null != comments.getScore()) {
					double scoreCount1 = (tResPackage.getScore() != null ? tResPackage.getScore() : 0) * (tResPackage.getScoreCount());
					double score1 = Double.parseDouble(
							String.valueOf((scoreCount1 + Long.parseLong(String.valueOf(comments.getScore())))))
							/ (tResPackage.getScoreCount() + 1);
					map.put("score", score1);
					map.put("scoreCount", 1);
				}
				if(comments.getContents() != null && comments.getContents().size() > 0){
					// 评论次数加1
					map.put("commentCount", 1);
				}
				tbTeachingResPackageDao.timesPlusOneById(map);
			} else {
				TbTeachingResPackage t = new TbTeachingResPackage();
				t.setPkid(pkid);
				t.setScore(Double.valueOf(comments.getScore()));
				t.setScoreCount(1);
				tbTeachingResPackageDao.save(t);
			}
		} else {
			Map<String, Object> map = new HashMap<String, Object>();
			String pkid = comments.getBusinessId();
			TbTeachingRes tRes = teachingResDao.getById(pkid);
			if(null != tRes){
				map.put("pkid", pkid);
				if ( null != comments.getScore()) {
					double scoreCount1 = (tRes.getScore() != null ? tRes.getScore() : 0) * (tRes.getScoreCount());
					double score1 = Double.parseDouble(
							String.valueOf((scoreCount1 + Long.parseLong(String.valueOf(comments.getScore())))))
							/ (tRes.getScoreCount() + 1);
					map.put("score", score1);
					map.put("scoreCount", 1);
				}
				if(comments.getContents() != null && comments.getContents().size() > 0){
					// 评论次数加1
					map.put("commentCount", 1);
				}
				teachingResDao.timesPlusOneById(map);
			} else {
				TbTeachingRes t = new TbTeachingRes();
				t.setId(pkid);
				t.setScore(Double.valueOf(comments.getScore()));
				t.setScoreCount(1);
				teachingResDao.save(t);
			}
		}

		resultMap.put("code", "0");
		return resultMap;
	}

    @Override
    public List<Map<String, Object>> getComment(CommentsReq commentsReq) throws Exception {
	    //查询评论
	    List<Map<String, Object>> commentsList = tbCommentsMapper.getComments(commentsReq);

	    if(null != commentsList && commentsList.size() > 0) {
	    	//查询评分
			for(Map<String, Object> m : commentsList) {
				TbScore score = tbCommentsMapper.getScore(commentsReq);
				if (null != score) {
					m.put("score", score.getScore());
				}
			}
		} else {
	    	return new ArrayList<Map<String, Object>>();
		}

        return commentsList;
    }

	@Override
	public List<Map<String, Object>> statComments(CommentsReq commentsReq) throws Exception {
		return tbCommentsMapper.statComments(commentsReq);
	}

	/**
	 * 敏感词过滤
	 */
	private String filterInfo(CommentsReq comments, com.alibaba.fastjson.JSONObject resultJson) {
		// 有敏感词,替换敏感词为*
		StringBuilder builder = new StringBuilder(comments.getContent());
		com.alibaba.fastjson.JSONArray words = resultJson.getJSONArray("words");
		if (words != null && words.size() > 0) {
			for (Object object : words) {
				com.alibaba.fastjson.JSONObject jsonObj = (com.alibaba.fastjson.JSONObject) object;
				com.alibaba.fastjson.JSONArray pos = jsonObj.getJSONArray("pos");
				if (pos != null && pos.size() > 0) {
					int start = 0;
					int end = 0;
					for (Object object2 : pos) {
						String posStr = (String) object2;
						String[] posStrArr = posStr.split(":");
						start = Integer.parseInt(posStrArr[0]);
						end = Integer.parseInt(posStrArr[1]);
						builder.replace(start, end, getReplaceStr(end - start));
					}
				}
			}
		}
		return builder.toString();
	}

	/**
	 * 根据敏感词长度,生成相同长度的 * 字符串
	 */
	private String getReplaceStr(int i) {
		StringBuilder builder = new StringBuilder(i);
		for (int j = 0; j < i; j++) {
			builder.append("*");
		}
		return builder.toString();
	}

	@Override
	public PageList<TbTeachingResPackage> ysykBagPageList(TeachingResPackageReq teachingResPackageReq) throws Exception {

		PageList<TbTeachingResPackage> pageList = new PageList<TbTeachingResPackage>();
		PageInfo pageInfo = teachingResPackageReq.getPageInfo();
		if (pageInfo == null) {
			pageInfo = new PageInfo();
		}
		if(null == teachingResPackageReq.getResType()){
			//默认不传查询一师优课资源包
			teachingResPackageReq.setResType(3);
		}
		String [] chapterIds = teachingResPackageReq.getChapterId().split(",");
		teachingResPackageReq.setChapterIds(chapterIds);
		teachingResPackageReq.setStart(pageInfo.getStart());
		teachingResPackageReq.setEnd(pageInfo.getEnd());
		teachingResPackageReq.setPageSize(pageInfo.getPageSize());
		int recordCount = tbTeachingResPackageDao.countYsykPageList(teachingResPackageReq);
		List<TbTeachingResPackage> list =  tbTeachingResPackageDao.selectYsykPageList(teachingResPackageReq);
		if(recordCount !=0){
			for(TbTeachingResPackage tbTeachingResPackage:list){
				TeachingResReq teachingResReq = new TeachingResReq();
				teachingResReq.setResType("3");
				teachingResReq.setSourcePackageId(tbTeachingResPackage.getPackageId());
				teachingResReq.setCourseType("1");
				StringBuilder classficationStr = new StringBuilder();
				int count1 = teachingResDao.countTeachingPageList(teachingResReq);
				if(count1>0){
					classficationStr.append("1");
				}else {
					classficationStr.append("0");
				}
				teachingResReq.setCourseType("2");
				int count2 = teachingResDao.countTeachingPageList(teachingResReq);
				if(count2>0){
					classficationStr.append(",").append("1");
				}else {
					classficationStr.append(",").append("0");
				}
				teachingResReq.setCourseType("3");
				int count3 = teachingResDao.countTeachingPageList(teachingResReq);
				if(count3>0){
					classficationStr.append(",").append("1");
				}else {
					classficationStr.append(",").append("0");
				}
				tbTeachingResPackage.setClassificationIds(classficationStr.toString());
			}
		}
		pageInfo.setRecordCount(recordCount);
		pageList.setPageInfo(pageInfo);
		pageList.setList(list);
		return pageList;
	}


	@Override
	public CloudPage<TbTeachingRes> teachingResPageList(TeachingResReq teachingResReq)throws Exception {
		CloudPage<TbTeachingRes> resPageList = new CloudPage<TbTeachingRes>();
		PageInfo pageInfo = teachingResReq.getPageInfo();
		if(null == pageInfo){
			pageInfo = new PageInfo();
		}
		int count = teachingResDao.countTeachingPageList(teachingResReq);
		pageInfo.setRecordCount(count);
		int totalPage = count/pageInfo.getPageSize();
		if(count%pageInfo.getPageSize()  > 0){
			totalPage = totalPage +1;
		}
		pageInfo.setTotalPage(totalPage);
		teachingResReq.setPageSize(pageInfo.getPageSize());
		teachingResReq.setStart(pageInfo.getStart());
		teachingResReq.setEnd(pageInfo.getEnd());
		List<TbTeachingRes> list = teachingResDao.teachingPageList(teachingResReq);
		resPageList.setPageInfo(pageInfo);
		resPageList.setList(list);
		return resPageList;
	}

	@Override
	public CloudPage<TbTeachingRes> jpzyResPageList(TeachingResReq teachingResReq)throws Exception {
		CloudPage<TbTeachingRes> resPageList = new CloudPage<TbTeachingRes>();
		PageInfo pageInfo = teachingResReq.getPageInfo();
		if(null == pageInfo){
			pageInfo = new PageInfo();
		}
		int count = teachingResDao.countJpzyPageList(teachingResReq);
		pageInfo.setRecordCount(count);
		int totalPage = count/pageInfo.getPageSize();
		if(count%pageInfo.getPageSize()  > 0){
			totalPage = totalPage +1;
		}
		pageInfo.setTotalPage(totalPage);
		teachingResReq.setPageSize(pageInfo.getPageSize());
		teachingResReq.setStart(pageInfo.getStart());
		teachingResReq.setEnd(pageInfo.getEnd());
		List<TbTeachingRes> list = teachingResDao.jpzyPageList(teachingResReq);
		resPageList.setPageInfo(pageInfo);
		resPageList.setList(list);
		return resPageList;
	}


	@Override
	public void timesPlusOneById(Map<String, Object> map) throws Exception {
//		String userId = map.get("userId").toString();
//		String userName = map.get("userName").toString();
//		String platformCode = map.get("platformCode").toString();
//		String loginPlatformCode = map.get("loginPlatformCode").toString();
//		String resType = map.get("resType").toString();
		String id  = map.get("id").toString();

//		if("1".equals(resType)){
//			tbCourseResMapper.plusOneForSharRes(map);
//		}else{
			map.put("pkid", id);
			teachingResDao.timesPlusOneById(map);
//		}
//		//调用大数据接口实时同步数据给推荐引擎；
//		synToBigData(id,resType);
	}

	@Override
	public TbTeachingRes getTeachingResById(TbTeachingRes param) {
		return teachingResDao.getTeachingResById(param);
	}

	@Override
	public void modTeachingResById(TbTeachingRes param) {
		teachingResDao.modTeachingResById(param);
	}
}
